package org.millioncall.yueyoga.admin.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.millioncall.openplatform.common.PaginatedList;
import org.millioncall.openplatform.util.StringUtils;
import org.millioncall.yueyoga.admin.dao.RoleDAO;
import org.millioncall.yueyoga.admin.model.Role;
import org.millioncall.yueyoga.admin.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDAO roleDAO;

	public RoleDAO getRoleDAO() {
		return roleDAO;
	}

	public void setRoleDAO(RoleDAO roleDAO) {
		this.roleDAO = roleDAO;
	}

	public List<Role> findRolesByGroupId(String strGpId) {
		int gpId = 0;
		if (StringUtils.isNotBlank(strGpId)) {
			gpId = Integer.parseInt(strGpId);
		}
		return roleDAO.findRolesByGroupId(gpId);
	}

	@Override
	public List<Role> findRoleAll() {
		return roleDAO.findRoleAll();
	}

	public PaginatedList<Role> getRolesInPage(int start, int limit,
			Map<String, Object> map) {
		return roleDAO.findRolesInPage(start, limit, map);
	}

	@Override
	public Role findRoleById(Integer id) {
		return roleDAO.findRoleById(id);
	}

	public boolean updateRole(Map<String, Object> map) {
		int i = roleDAO.updateRole(map);
		if (i > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public boolean saveRole(Map<String, Object> map) {
		int i = roleDAO.saveRole(map);
		if (i > 0) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void deleteRoleByIds(int[] id) {
		if (id == null || id.length == 0) {
			throw new RuntimeException(" 未提交要删除角色");
		} else {
			this.roleDAO.deleteRoleByIds(id);
		}
	}

	public void deleteRoleGroupById(int[] id) {
		if (id == null || id.length == 0) {
			throw new RuntimeException(" 未提交要删除角色");
		} else {
			this.roleDAO.deleteRoleGroupById(id);
		}
	}

	@Override
	public boolean grantRoleAuthorities(String roleId, String auIds) {
		if (StringUtils.isNotBlank(roleId) && StringUtils.isNotBlank(auIds)) {
			int count = 0;
			Map<String, String> map = new HashMap<String, String>();
			String[] ids = auIds.split(",");
			count = roleDAO.deleteRoleAuthorities(Integer.valueOf(roleId));
			map.put("roleId", roleId);
			map.put("enabled", "1");
			if (ids != null && ids.length > 0) {
				for (String auId : ids) {
					if (StringUtils.isNotBlank(auId)) {
						map.put("auId", auId);
						count += roleDAO.saveRoleAuthority(map);
						map.remove("auId");
					}
				}
			}
			return count > 0;
		}
		return false;
	}

	@Override
	public Role findRoleByName(String name) {
		return roleDAO.findRoleByName(name);
	}
}
